package com.eduagent.xwqeduagent.app.student.ExerciseEvaluationAssistant;

import com.eduagent.xwqeduagent.adviser.MyLoggerAdvisor;
import com.eduagent.xwqeduagent.constant.prompt.ExerciseEvaluationSystem;
import com.eduagent.xwqeduagent.model.dto.ExerciseEvaluationRequest;
import com.eduagent.xwqeduagent.model.vo.ExerciseEvaluationVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

@Component
@Slf4j
public class ExerciseEvaluationAssistant {

    private final ChatClient chatClient;

    @Resource
    private ToolCallback[] allTools;

    @Resource
    private ToolCallbackProvider toolCallbackProvider;

    @Resource
    private Advisor loveAppRagCloudAdvisor;

    // 缓存学生练习相关信息，用于上下文连续对话和总结分析
    private final Map<String, Map<String, Object>> exerciseSessionCache = new HashMap<>();

    private final ObjectMapper objectMapper = new ObjectMapper();

    public ExerciseEvaluationAssistant(ChatModel dashscopeChatModel) {
        String exercisePrompt = ExerciseEvaluationSystem.EXERCISE_EVALUATION_PROMPT;
        chatClient = ChatClient.builder(dashscopeChatModel)
                .defaultSystem(exercisePrompt)
                .defaultAdvisors(
                        // 自定义日志Advisor
                        new MyLoggerAdvisor()
                )
                .build();
    }

    /**
     * 处理学生练习中的问题请求
     *
     * @param question 学生问题
     * @param exerciseContent 练习题目内容
     * @param subject 学科/主题
     * @param sessionId 会话ID
     * @return 解题思路指导
     */
    public ExerciseEvaluationVO provideExerciseGuidance(String question,
                                                      String exerciseContent,
                                                      String subject,
                                                      String sessionId) {
        // 构建提示词
        String promptTemplate = ExerciseEvaluationSystem.QUESTION_GUIDANCE_PROMPT;
        String userQuery = promptTemplate
                .replace("{{exerciseContent}}", exerciseContent)
                .replace("{{question}}", question)
                .replace("{{subject}}", subject);
        
        log.info("收到练习指导请求：{}", question);
        
        // 更新或初始化会话缓存
        updateSessionCache(sessionId, "exerciseContent", exerciseContent);
        updateSessionCache(sessionId, "subject", subject);
        updateSessionCache(sessionId, "lastQuestion", question);
        
        // 调用AI获取解题思路
        ChatResponse chatResponse = chatClient
                .prompt()
                .user(userQuery)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, sessionId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 20))
                .advisors(new MyLoggerAdvisor())
                .advisors(loveAppRagCloudAdvisor) // 使用RAG顾问增强回答质量
                .tools(allTools)
                .call()
                .chatResponse();
        
        String guidance = chatResponse.getResult().getOutput().getText();
        log.info("解题思路生成完成，长度：{}", guidance.length());
        
        // 构建返回对象
        ExerciseEvaluationVO result = new ExerciseEvaluationVO();
        result.setResponseType("GUIDANCE");
        result.setContent(guidance);
        
        return result;
    }

    /**
     * 评测学生答案
     *
     * @param studentAnswer 学生答案
     * @param exerciseContent 练习题目内容
     * @param correctAnswer 正确答案
     * @param subject 学科/主题
     * @param sessionId 会话ID
     * @return 评测结果
     */
    public ExerciseEvaluationVO evaluateStudentAnswer(String studentAnswer,
                                                    String exerciseContent,
                                                    String correctAnswer,
                                                    String subject,
                                                    String sessionId) {
        // 构建提示词
        String promptTemplate = ExerciseEvaluationSystem.ANSWER_EVALUATION_PROMPT;
        String userQuery = promptTemplate
                .replace("{{exerciseContent}}", exerciseContent)
                .replace("{{studentAnswer}}", studentAnswer)
                .replace("{{correctAnswer}}", correctAnswer)
                .replace("{{subject}}", subject);
        
        log.info("收到答案评测请求，题目内容长度：{}", exerciseContent.length());
        
        // 更新会话缓存
        updateSessionCache(sessionId, "exerciseContent", exerciseContent);
        updateSessionCache(sessionId, "correctAnswer", correctAnswer);
        updateSessionCache(sessionId, "subject", subject);
        updateSessionCache(sessionId, "lastStudentAnswer", studentAnswer);
        
        // 记录本次练习结果，用于后续总结
        Map<String, Object> exerciseRecord = new HashMap<>();
        exerciseRecord.put("exerciseContent", exerciseContent);
        exerciseRecord.put("studentAnswer", studentAnswer);
        exerciseRecord.put("correctAnswer", correctAnswer);
        
        List<Map<String, Object>> exerciseHistory = (List<Map<String, Object>>) 
                getSessionCache(sessionId).getOrDefault("exerciseHistory", new ArrayList<>());
        exerciseHistory.add(exerciseRecord);
        updateSessionCache(sessionId, "exerciseHistory", exerciseHistory);
        
        // 调用AI评测答案
        ChatResponse chatResponse = chatClient
                .prompt()
                .user(userQuery)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, sessionId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 20))
                .advisors(new MyLoggerAdvisor())
                .tools(allTools)
                .call()
                .chatResponse();
        
        String evaluation = chatResponse.getResult().getOutput().getText();
        log.info("评测结果生成完成，长度：{}", evaluation.length());
        
        // 解析评测结果
        ExerciseEvaluationVO result = new ExerciseEvaluationVO();
        result.setResponseType("EVALUATION");
        result.setContent(evaluation);
        
        // 尝试提取评分
        Integer score = extractScoreFromEvaluation(evaluation);
        if (score != null) {
            result.setScore(score);
            
            // 根据分数判断是否需要错误分析
            if (score < 90) {
                String errorAnalysis = extractErrorAnalysisFromEvaluation(evaluation);
                result.setErrorAnalysis(errorAnalysis);
            }
        }
        
        // 提取学习建议
        List<String> suggestions = extractSuggestionsFromEvaluation(evaluation);
        if (!suggestions.isEmpty()) {
            result.setSuggestions(suggestions);
        }
        
        return result;
    }

    /**
     * 批量评测学生答案
     *
     * @param submissions 多题目提交列表
     * @param subject 学科/主题
     * @param sessionId 会话ID
     * @return 评测结果
     */
    public ExerciseEvaluationVO evaluateMultipleAnswers(
            List<ExerciseEvaluationRequest.ExerciseSubmission> submissions,
            String subject,
            String sessionId) {
        
        log.info("收到批量答案评测请求，题目数量：{}", submissions.size());
        
        // 准备批量评测结果
        ExerciseEvaluationVO result = new ExerciseEvaluationVO();
        result.setResponseType("EVALUATION");
        
        List<ExerciseEvaluationVO.QuestionEvaluation> evaluationResults = new ArrayList<>();
        double totalFullScore = 0;
        double totalEarnedScore = 0;
        
        // 构建整体提示词
        StringBuilder promptBuilder = new StringBuilder();
        promptBuilder.append("你是一名专业的教育评测助手，请对以下").append(submissions.size()).append("道")
                .append(subject).append("题目的学生答案进行评测。\n\n");
        
        // 为每道题添加内容
        for (int i = 0; i < submissions.size(); i++) {
            ExerciseEvaluationRequest.ExerciseSubmission submission = submissions.get(i);
            
            promptBuilder.append("题目").append(i + 1).append("：").append(submission.getQuestionText()).append("\n");
            promptBuilder.append("题目类型：").append(submission.getType()).append("\n");
            promptBuilder.append("学生答案：").append(submission.getStudentAnswer()).append("\n");
            promptBuilder.append("正确答案：").append(submission.getCorrectAnswer()).append("\n");
            promptBuilder.append("题目分值：").append(submission.getScore()).append("\n\n");
            
            // 记录总分
            totalFullScore += submission.getScore();
        }
        
        promptBuilder.append("请按照以下JSON格式返回评测结果：\n");
        promptBuilder.append("```json\n");
        promptBuilder.append("{\n");
        promptBuilder.append("  \"overallEvaluation\": \"整体评价\",\n");
        promptBuilder.append("  \"totalScore\": 100.0,\n");
        promptBuilder.append("  \"earnedScore\": 85.0,\n");
        promptBuilder.append("  \"questions\": [\n");
        promptBuilder.append("    {\n");
        promptBuilder.append("      \"questionId\": \"题目ID\",\n");
        promptBuilder.append("      \"isCorrect\": true,\n");
        promptBuilder.append("      \"score\": 10.0,\n");
        promptBuilder.append("      \"fullScore\": 10.0,\n");
        promptBuilder.append("      \"explanation\": \"解析\",\n");
        promptBuilder.append("      \"errorAnalysis\": \"错误分析（如有）\"\n");
        promptBuilder.append("    },\n");
        promptBuilder.append("    // 更多题目...\n");
        promptBuilder.append("  ],\n");
        promptBuilder.append("  \"suggestions\": [\"建议1\", \"建议2\", \"建议3\"]\n");
        promptBuilder.append("}\n");
        promptBuilder.append("```\n");
        
        // 调用AI批量评测答案
        ChatResponse chatResponse = chatClient
                .prompt()
                .user(promptBuilder.toString())
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, sessionId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 20))
                .advisors(new MyLoggerAdvisor())
                .tools(allTools)
                .call()
                .chatResponse();
        
        String evaluation = chatResponse.getResult().getOutput().getText();
        log.info("批量评测结果生成完成，长度：{}", evaluation.length());
        
        // 解析评测JSON结果
        try {
            // 提取JSON部分
            String jsonContent = extractJsonContent(evaluation);
            Map<String, Object> evaluationMap = objectMapper.readValue(jsonContent, new TypeReference<Map<String, Object>>() {});
            
            // 设置总体评价
            result.setOverallEvaluation((String) evaluationMap.get("overallEvaluation"));
            
            // 设置总分和得分
            if (evaluationMap.containsKey("totalScore")) {
                Object totalScoreObj = evaluationMap.get("totalScore");
                if (totalScoreObj instanceof Number) {
                    result.setTotalScore(((Number) totalScoreObj).doubleValue());
                }
            } else {
                result.setTotalScore(totalFullScore);
            }
            
            if (evaluationMap.containsKey("earnedScore")) {
                Object earnedScoreObj = evaluationMap.get("earnedScore");
                if (earnedScoreObj instanceof Number) {
                    result.setEarnedScore(((Number) earnedScoreObj).doubleValue());
                }
            }
            
            // 设置建议
            if (evaluationMap.containsKey("suggestions") && evaluationMap.get("suggestions") instanceof List) {
                @SuppressWarnings("unchecked")
                List<String> suggestions = (List<String>) evaluationMap.get("suggestions");
                result.setSuggestions(suggestions);
            }
            
            // 处理每道题的评测结果
            if (evaluationMap.containsKey("questions") && evaluationMap.get("questions") instanceof List) {
                @SuppressWarnings("unchecked")
                List<Map<String, Object>> questionsEval = (List<Map<String, Object>>) evaluationMap.get("questions");
                
                for (int i = 0; i < Math.min(questionsEval.size(), submissions.size()); i++) {
                    Map<String, Object> questionEval = questionsEval.get(i);
                    ExerciseEvaluationRequest.ExerciseSubmission submission = submissions.get(i);
                    
                    ExerciseEvaluationVO.QuestionEvaluation evalResult = new ExerciseEvaluationVO.QuestionEvaluation();
                    evalResult.setQuestionId(submission.getQuestionId());
                    evalResult.setQuestionText(submission.getQuestionText());
                    evalResult.setType(submission.getType());
                    evalResult.setStudentAnswer(submission.getStudentAnswer());
                    
                    // 设置正确答案
                    List<String> correctAnswers = new ArrayList<>();
                    correctAnswers.add(submission.getCorrectAnswer());
                    evalResult.setCorrectAnswers(correctAnswers);
                    
                    // 设置得分
                    if (questionEval.containsKey("score")) {
                        Object scoreObj = questionEval.get("score");
                        if (scoreObj instanceof Number) {
                            evalResult.setScore(((Number) scoreObj).doubleValue());
                            totalEarnedScore += evalResult.getScore();
                        }
                    }
                    
                    // 设置满分
                    evalResult.setFullScore(submission.getScore());
                    
                    // 设置是否正确
                    if (questionEval.containsKey("isCorrect")) {
                        evalResult.setIsCorrect((Boolean) questionEval.get("isCorrect"));
                    }
                    
                    // 设置解析
                    evalResult.setExplanation((String) questionEval.get("explanation"));
                    
                    // 设置错误分析
                    if (!evalResult.getIsCorrect()) {
                        evalResult.setErrorAnalysis((String) questionEval.get("errorAnalysis"));
                    }
                    
                    evaluationResults.add(evalResult);
                }
            }
            
            // 如果AI没有计算总得分，使用我们自己累加的
            if (result.getEarnedScore() == null) {
                result.setEarnedScore(totalEarnedScore);
            }
            
        } catch (Exception e) {
            log.error("解析批量评测JSON结果失败", e);
            // 提供基本评测内容
            result.setContent(evaluation);
        }
        
        // 设置最终评测结果
        result.setEvaluationResults(evaluationResults);
        
        // 更新会话缓存，记录本次练习结果
        for (ExerciseEvaluationRequest.ExerciseSubmission submission : submissions) {
            Map<String, Object> exerciseRecord = new HashMap<>();
            exerciseRecord.put("exerciseContent", submission.getQuestionText());
            exerciseRecord.put("studentAnswer", submission.getStudentAnswer());
            exerciseRecord.put("correctAnswer", submission.getCorrectAnswer());
            
            List<Map<String, Object>> exerciseHistory = (List<Map<String, Object>>) 
                    getSessionCache(sessionId).getOrDefault("exerciseHistory", new ArrayList<>());
            exerciseHistory.add(exerciseRecord);
            updateSessionCache(sessionId, "exerciseHistory", exerciseHistory);
        }
        
        return result;
    }

    /**
     * 总结学习情况
     *
     * @param sessionId 会话ID
     * @return 总结结果
     */
    public ExerciseEvaluationVO summarizeLearningSession(String sessionId) {
        // 构建提示词
        String promptTemplate = ExerciseEvaluationSystem.SUMMARY_PROMPT;
        
        log.info("收到学习总结请求，会话ID：{}", sessionId);
        
        // 调用AI生成总结
        ChatResponse chatResponse = chatClient
                .prompt()
                .system(promptTemplate)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, sessionId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 50)) // 获取更多历史上下文以进行全面总结
                .advisors(new MyLoggerAdvisor())
                .tools(allTools)
                .call()
                .chatResponse();
        
        String summary = chatResponse.getResult().getOutput().getText();
        log.info("学习总结生成完成，长度：{}", summary.length());
        
        // 构建返回对象
        ExerciseEvaluationVO result = new ExerciseEvaluationVO();
        result.setResponseType("SUMMARY");
        result.setContent(summary);
        
        // 提取学习建议
        List<String> suggestions = extractSuggestionsFromEvaluation(summary);
        if (!suggestions.isEmpty()) {
            result.setSuggestions(suggestions);
        }
        
        return result;
    }

    /**
     * 总结学习情况（基于前端传入的会话结果）
     *
     * @param sessionResult 会话结果
     * @param subject 学科/主题
     * @param sessionId 会话ID
     * @return 总结结果
     */
    public ExerciseEvaluationVO summarizeLearningSessionWithResults(
            ExerciseEvaluationRequest.ExerciseSessionResult sessionResult,
            String subject,
            String sessionId) {
        
        log.info("收到带有会话结果的学习总结请求，会话ID：{}", sessionId);
        
        // 构建提示词
        StringBuilder promptBuilder = new StringBuilder();
        promptBuilder.append("请根据以下学生在").append(subject).append("练习中的表现，提供一份详细的学习总结和针对性的学习建议。\n\n");
        
        // 添加总体成绩信息
        promptBuilder.append("练习总体情况：\n");
        promptBuilder.append("- 总分：").append(sessionResult.getTotalScore()).append("\n");
        promptBuilder.append("- 获得分数：").append(sessionResult.getEarnedScore()).append("\n");
        promptBuilder.append("- 正确率：").append(
                String.format("%.2f%%", sessionResult.getEarnedScore() / sessionResult.getTotalScore() * 100)
        ).append("\n\n");
        
        // 添加各题目的详细情况
        promptBuilder.append("各题目完成情况：\n");
        if (!CollectionUtils.isEmpty(sessionResult.getQuestionResults())) {
            for (int i = 0; i < sessionResult.getQuestionResults().size(); i++) {
                ExerciseEvaluationRequest.ExerciseSessionResult.QuestionResult question = 
                        sessionResult.getQuestionResults().get(i);
                
                promptBuilder.append(i + 1).append(". 题目：").append(question.getQuestionText()).append("\n");
                promptBuilder.append("   题型：").append(question.getType()).append("\n");
                promptBuilder.append("   学生答案：").append(question.getStudentAnswer()).append("\n");
                promptBuilder.append("   正确答案：").append(question.getCorrectAnswer()).append("\n");
                promptBuilder.append("   是否正确：").append(question.getIsCorrect() ? "正确" : "错误").append("\n");
                promptBuilder.append("   得分：").append(question.getScore()).append("/").append(question.getFullScore()).append("\n");
                
                if (question.getKnowledgePoints() != null && !question.getKnowledgePoints().isEmpty()) {
                    promptBuilder.append("   相关知识点：").append(String.join("、", question.getKnowledgePoints())).append("\n");
                }
                
                promptBuilder.append("\n");
            }
        }
        
        // 添加总结要求
        promptBuilder.append("请提供以下内容：\n");
        promptBuilder.append("1. 总体表现评价\n");
        promptBuilder.append("2. 知识掌握情况分析（优势与不足）\n");
        promptBuilder.append("3. 3-5条具体学习建议\n");
        promptBuilder.append("4. 鼓励性总结语\n");
        
        // 调用AI生成总结
        ChatResponse chatResponse = chatClient
                .prompt()
                .user(promptBuilder.toString())
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, sessionId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10)) // 不需要太多历史上下文，因为我们已经提供了完整的练习情况
                .advisors(new MyLoggerAdvisor())
                .tools(allTools)
                .call()
                .chatResponse();
        
        String summary = chatResponse.getResult().getOutput().getText();
        log.info("学习总结生成完成，长度：{}", summary.length());
        
        // 构建返回对象
        ExerciseEvaluationVO result = new ExerciseEvaluationVO();
        result.setResponseType("SUMMARY");
        result.setContent(summary);
        
        // 提取学习建议
        List<String> suggestions = extractSuggestionsFromEvaluation(summary);
        if (!suggestions.isEmpty()) {
            result.setSuggestions(suggestions);
        }
        
        // 保存总结到会话缓存中
        updateSessionCache(sessionId, "lastSummary", summary);
        updateSessionCache(sessionId, "lastPerformance", sessionResult);
        
        return result;
    }
    
    /**
     * 生成强化训练题目
     *
     * @param subject 学科/主题
     * @param sessionId 会话ID
     * @return 强化训练题目
     */
    public ExerciseEvaluationVO generateReinforcementExercises(String subject, String sessionId) {
        // 构建提示词
        String promptTemplate = ExerciseEvaluationSystem.REINFORCEMENT_PROMPT;
        String userQuery = promptTemplate.replace("{{subject}}", subject);
        
        log.info("收到强化训练生成请求，学科：{}", subject);
        
        // 调用AI生成强化训练题目
        ChatResponse chatResponse = chatClient
                .prompt()
                .user(userQuery)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, sessionId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 50)) // 获取历史上下文以生成针对性题目
                .advisors(new MyLoggerAdvisor())
                .tools(allTools)
                .call()
                .chatResponse();
        
        String exercisesContent = chatResponse.getResult().getOutput().getText();
        log.info("强化训练题目生成完成，长度：{}", exercisesContent.length());
        
        // 构建返回对象
        ExerciseEvaluationVO result = new ExerciseEvaluationVO();
        result.setResponseType("EXERCISE");
        result.setContent(exercisesContent);
        
        // 解析生成的强化训练题目
        List<ExerciseEvaluationVO.ExerciseItem> exerciseItems = parseGeneratedExercises(exercisesContent);
        result.setExerciseItems(exerciseItems);
        
        return result;
    }
    
    /**
     * 生成强化训练题目（基于前端传入的会话结果）
     *
     * @param sessionResult 会话结果
     * @param subject 学科/主题
     * @param sessionId 会话ID
     * @return 强化训练题目
     */
    public ExerciseEvaluationVO generateReinforcementExercisesWithResults(
            ExerciseEvaluationRequest.ExerciseSessionResult sessionResult,
            String subject,
            String sessionId) {
        
        log.info("收到带有会话结果的强化训练生成请求，学科：{}", subject);
        
        // 确定需要强化的知识点
        Set<String> weakKnowledgePoints = new HashSet<>();
        Set<String> allKnowledgePoints = new HashSet<>();
        
        if (!CollectionUtils.isEmpty(sessionResult.getQuestionResults())) {
            for (ExerciseEvaluationRequest.ExerciseSessionResult.QuestionResult question : 
                    sessionResult.getQuestionResults()) {
                
                // 如果题目答错或得分低于70%，将相关知识点加入需要强化的集合
                if (!question.getIsCorrect() || 
                        (question.getScore() / question.getFullScore() < 0.7)) {
                    
                    if (!CollectionUtils.isEmpty(question.getKnowledgePoints())) {
                        weakKnowledgePoints.addAll(question.getKnowledgePoints());
                    }
                }
                
                // 收集所有知识点
                if (!CollectionUtils.isEmpty(question.getKnowledgePoints())) {
                    allKnowledgePoints.addAll(question.getKnowledgePoints());
                }
            }
        }
        
        // 如果没有明确的弱点知识点，使用所有知识点
        if (weakKnowledgePoints.isEmpty() && !allKnowledgePoints.isEmpty()) {
            weakKnowledgePoints.addAll(allKnowledgePoints);
        }
        
        // 构建提示词
        String promptTemplate = ExerciseEvaluationSystem.REINFORCEMENT_PROMPT;
        
        // 添加学生表现和知识点信息
        StringBuilder userPromptBuilder = new StringBuilder();
        userPromptBuilder.append("学科/主题：").append(subject).append("\n");
        
        // 添加需要强化的知识点
        if (!weakKnowledgePoints.isEmpty()) {
            userPromptBuilder.append("需要强化的知识点：").append(String.join("、", weakKnowledgePoints)).append("\n\n");
        } else {
            userPromptBuilder.append("需要强化的知识点：基于学生整体表现分析确定\n\n");
        }
        
        // 添加学生表现概况
        userPromptBuilder.append("学生练习表现概况：\n");
        userPromptBuilder.append("- 总分：").append(sessionResult.getTotalScore()).append("\n");
        userPromptBuilder.append("- 获得分数：").append(sessionResult.getEarnedScore()).append("\n");
        userPromptBuilder.append("- 正确率：").append(
                String.format("%.2f%%", sessionResult.getEarnedScore() / sessionResult.getTotalScore() * 100)
        ).append("\n\n");
        
        // 添加错题信息
        if (!CollectionUtils.isEmpty(sessionResult.getQuestionResults())) {
            userPromptBuilder.append("学生错题情况：\n");
            boolean hasIncorrectAnswers = false;
            
            for (ExerciseEvaluationRequest.ExerciseSessionResult.QuestionResult question : 
                    sessionResult.getQuestionResults()) {
                
                if (!question.getIsCorrect()) {
                    hasIncorrectAnswers = true;
                    userPromptBuilder.append("- 题目：").append(question.getQuestionText()).append("\n");
                    userPromptBuilder.append("  学生答案：").append(question.getStudentAnswer()).append("\n");
                    userPromptBuilder.append("  正确答案：").append(question.getCorrectAnswer()).append("\n");
                    if (!CollectionUtils.isEmpty(question.getKnowledgePoints())) {
                        userPromptBuilder.append("  相关知识点：").append(String.join("、", question.getKnowledgePoints())).append("\n");
                    }
                    userPromptBuilder.append("\n");
                }
            }
            
            if (!hasIncorrectAnswers) {
                userPromptBuilder.append("学生没有明显的错题，请基于相关知识点生成提高难度的习题。\n\n");
            }
        }
        
        String userQuery = promptTemplate.replace("{{subject}}", subject) + "\n\n" + userPromptBuilder.toString();
        
        // 调用AI生成强化训练题目
        ChatResponse chatResponse = chatClient
                .prompt()
                .user(userQuery)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, sessionId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10)) // 不需要太多历史上下文
                .advisors(new MyLoggerAdvisor())
                .tools(allTools)
                .call()
                .chatResponse();
        
        String exercisesContent = chatResponse.getResult().getOutput().getText();
        log.info("强化训练题目生成完成，长度：{}", exercisesContent.length());
        
        // 构建返回对象
        ExerciseEvaluationVO result = new ExerciseEvaluationVO();
        result.setResponseType("EXERCISE");
        result.setContent(exercisesContent);
        
        // 解析生成的强化训练题目
        List<ExerciseEvaluationVO.ExerciseItem> exerciseItems = parseGeneratedExercises(exercisesContent);
        result.setExerciseItems(exerciseItems);
        
        return result;
    }
    
    /**
     * 更新会话缓存
     */
    private void updateSessionCache(String sessionId, String key, Object value) {
        Map<String, Object> sessionCache = exerciseSessionCache.getOrDefault(sessionId, new HashMap<>());
        sessionCache.put(key, value);
        exerciseSessionCache.put(sessionId, sessionCache);
    }
    
    /**
     * 获取会话缓存
     */
    private Map<String, Object> getSessionCache(String sessionId) {
        return exerciseSessionCache.getOrDefault(sessionId, new HashMap<>());
    }
    
    /**
     * 从评测结果中提取分数
     */
    private Integer extractScoreFromEvaluation(String evaluation) {
        // 使用正则表达式匹配评分（如：80分、得分：90、成绩：85/100等模式）
        Pattern pattern = Pattern.compile("(?:评分|得分|分数|成绩)[：:]*\\s*(\\d+)(?:\\s*[/／]\\s*100)?");
        Matcher matcher = pattern.matcher(evaluation);
        
        if (matcher.find()) {
            try {
                int score = Integer.parseInt(matcher.group(1));
                // 确保分数在0-100范围内
                return Math.max(0, Math.min(100, score));
            } catch (NumberFormatException e) {
                log.error("解析评分失败", e);
            }
        }
        return null;
    }
    
    /**
     * 从评测结果中提取错误分析部分
     */
    private String extractErrorAnalysisFromEvaluation(String evaluation) {
        // 尝试提取错误分析部分，一般在"错误分析"、"问题分析"等关键词后面
        String[] keywords = {"错误分析", "问题分析", "错误之处", "存在问题", "需要改进"};
        
        for (String keyword : keywords) {
            int index = evaluation.indexOf(keyword);
            if (index != -1) {
                // 找到关键词后，尝试提取到下一个段落或小节开始
                int endIndex = evaluation.indexOf("\n\n", index + keyword.length());
                if (endIndex == -1) {
                    endIndex = evaluation.length();
                }
                return evaluation.substring(index, endIndex).trim();
            }
        }
        
        // 如果没找到明确的错误分析段落，返回评测结果的后半部分
        if (evaluation.length() > 100) {
            return evaluation.substring(evaluation.length() / 2);
        }
        
        return "";
    }
    
    /**
     * 从评测或总结中提取学习建议
     */
    private List<String> extractSuggestionsFromEvaluation(String text) {
        List<String> suggestions = new ArrayList<>();
        
        // 查找建议部分
        int suggestionIndex = -1;
        String[] suggestionKeywords = {"建议", "改进建议", "学习建议", "提升建议"};
        
        for (String keyword : suggestionKeywords) {
            int index = text.indexOf(keyword);
            if (index != -1 && (suggestionIndex == -1 || index < suggestionIndex)) {
                suggestionIndex = index;
            }
        }
        
        if (suggestionIndex != -1) {
            // 提取建议段落
            String suggestionPart = text.substring(suggestionIndex);
            
            // 尝试按编号分割建议（如：1. xxx 2. yyy）
            Pattern pattern = Pattern.compile("\\d+[.、]\\s*([^\\d.、][^\\n]+)");
            Matcher matcher = pattern.matcher(suggestionPart);
            
            while (matcher.find() && suggestions.size() < 10) {
                suggestions.add(matcher.group(1).trim());
            }
            
            // 如果没有找到编号格式的建议，尝试按段落分割
            if (suggestions.isEmpty()) {
                String[] paragraphs = suggestionPart.split("\\n+");
                for (int i = 1; i < paragraphs.length && suggestions.size() < 5; i++) {
                    String paragraph = paragraphs[i].trim();
                    if (!paragraph.isEmpty() && !paragraph.startsWith("总结") && paragraph.length() > 10) {
                        suggestions.add(paragraph);
                    }
                }
            }
        }
        
        return suggestions;
    }
    
    /**
     * 解析生成的强化训练题目
     */
    private List<ExerciseEvaluationVO.ExerciseItem> parseGeneratedExercises(String exercisesContent) {
        List<ExerciseEvaluationVO.ExerciseItem> exercises = new ArrayList<>();
        
        try {
            // 尝试提取JSON部分
            String jsonContent = extractJsonContent(exercisesContent);
            
            // 解析JSON数组
            List<Map<String, Object>> exercisesList = objectMapper.readValue(
                    jsonContent, new TypeReference<List<Map<String, Object>>>() {});
            
            for (Map<String, Object> exercise : exercisesList) {
                ExerciseEvaluationVO.ExerciseItem item = new ExerciseEvaluationVO.ExerciseItem();
                
                // 设置通用ID
                item.setId(UUID.randomUUID().toString().substring(0, 8));
                
                // 映射基本字段
                item.setQuestionText((String) exercise.get("questionText"));
                item.setType((String) exercise.get("type"));
                item.setExplanation((String) exercise.get("explanation"));
                item.setDifficulty((String) exercise.get("difficulty"));
                item.setRemarks((String) exercise.get("remarks"));
                item.setMediaUrl((String) exercise.get("mediaUrl"));
                
                // 转换分数
                Object scoreObj = exercise.get("score");
                if (scoreObj != null) {
                    if (scoreObj instanceof Integer) {
                        item.setScore(((Integer) scoreObj).doubleValue());
                    } else if (scoreObj instanceof Double) {
                        item.setScore((Double) scoreObj);
                    }
                }
                
                // 转换选项
                Object optionsObj = exercise.get("options");
                if (optionsObj != null && optionsObj instanceof Map) {
                    @SuppressWarnings("unchecked")
                    Map<String, String> options = (Map<String, String>) optionsObj;
                    item.setOptions(options);
                }
                
                // 转换正确答案
                Object correctAnswersObj = exercise.get("correctAnswers");
                if (correctAnswersObj != null && correctAnswersObj instanceof List) {
                    @SuppressWarnings("unchecked")
                    List<String> correctAnswers = (List<String>) correctAnswersObj;
                    item.setCorrectAnswers(correctAnswers);
                }
                
                // 转换知识点
                Object knowledgePointsObj = exercise.get("knowledgePoints");
                if (knowledgePointsObj != null && knowledgePointsObj instanceof List) {
                    @SuppressWarnings("unchecked")
                    List<String> knowledgePoints = (List<String>) knowledgePointsObj;
                    item.setKnowledgePoints(knowledgePoints);
                }
                
                exercises.add(item);
            }
            
            log.info("成功解析强化训练题目，数量：{}", exercises.size());
        } catch (Exception e) {
            log.error("解析JSON格式题目失败，尝试使用备用解析方法", e);
            // 备用解析方法，使用原来的正则表达式解析
            exercises = parseExercisesWithRegex(exercisesContent);
        }
        
        return exercises;
    }
    
    /**
     * 从文本中提取JSON内容
     */
    private String extractJsonContent(String content) {
        // 尝试查找JSON数组开始和结束的位置
        int startIndex = content.indexOf('[');
        int endIndex = content.lastIndexOf(']') + 1;
        
        if (startIndex >= 0 && endIndex > startIndex) {
            return content.substring(startIndex, endIndex);
        }
        
        // 如果找不到完整的JSON数组，可能是格式问题，尝试修复或抛出异常
        throw new IllegalArgumentException("无法从内容中提取有效的JSON数组");
    }
    
    /**
     * 使用正则表达式解析练习题目（备用方法）
     */
    private List<ExerciseEvaluationVO.ExerciseItem> parseExercisesWithRegex(String exercisesContent) {
        List<ExerciseEvaluationVO.ExerciseItem> exercises = new ArrayList<>();
        
        // 使用正则表达式匹配题目格式
        // 预期格式如：题目1：xxx 答案：xxx 难度：3
        Pattern exercisePattern = Pattern.compile("题目\\s*(\\d+)\\s*[：:](.*?)(?:答案|参考答案)[：:](.*?)(?:难度[：:]\\s*(\\d))?(?=题目\\s*\\d+\\s*[：:]|$)", 
                Pattern.DOTALL);
        Matcher matcher = exercisePattern.matcher(exercisesContent);
        
        int count = 0;
        while (matcher.find() && count < 10) { // 限制最多解析10道题
            ExerciseEvaluationVO.ExerciseItem item = new ExerciseEvaluationVO.ExerciseItem();
            item.setId(UUID.randomUUID().toString().substring(0, 8));
            item.setQuestionText(matcher.group(2).trim());
            
            // 设置正确答案列表
            List<String> answers = new ArrayList<>();
            answers.add(matcher.group(3).trim());
            item.setCorrectAnswers(answers);
            
            // 设置答案解析
            item.setExplanation("参考答案：" + matcher.group(3).trim());
            
            // 解析难度级别，默认为MEDIUM
            String difficultyStr = matcher.groupCount() >= 4 && matcher.group(4) != null 
                    ? matcher.group(4).trim() : "3";
            try {
                int difficultyNum = Integer.parseInt(difficultyStr);
                // 将1-5的难度转换为EASY, MEDIUM, HARD
                if (difficultyNum <= 2) {
                    item.setDifficulty("EASY");
                } else if (difficultyNum <= 4) {
                    item.setDifficulty("MEDIUM");
                } else {
                    item.setDifficulty("HARD");
                }
            } catch (NumberFormatException e) {
                item.setDifficulty("MEDIUM"); // 默认中等难度
            }
            
            // 设置默认题型为SHORT_ANSWER
            item.setType("SHORT_ANSWER");
            
            // 设置默认分数
            item.setScore(5.0);
            
            exercises.add(item);
            count++;
        }
        
        // 如果正则没有匹配到，尝试更宽松的匹配方式
        if (exercises.isEmpty()) {
            // 简单地按"题目"关键词分割
            String[] parts = exercisesContent.split("(?i)题目\\s*\\d+[：:]");
            for (int i = 1; i < parts.length && i <= 5; i++) { // 跳过首个空白部分，最多5题
                String part = parts[i].trim();
                
                int answerIndex = Math.max(part.indexOf("答案："), part.indexOf("参考答案："));
                if (answerIndex == -1) {
                    answerIndex = part.length();
                }
                
                ExerciseEvaluationVO.ExerciseItem item = new ExerciseEvaluationVO.ExerciseItem();
                item.setId(UUID.randomUUID().toString().substring(0, 8));
                item.setQuestionText(part.substring(0, answerIndex).trim());
                
                // 设置正确答案列表
                List<String> answers = new ArrayList<>();
                String answerText = answerIndex < part.length() ? 
                        part.substring(answerIndex).replaceFirst("(?:答案|参考答案)[：:]\\s*", "") : "";
                answers.add(answerText);
                item.setCorrectAnswers(answers);
                
                // 设置答案解析
                item.setExplanation("参考答案：" + answerText);
                
                // 设置默认值
                item.setDifficulty("MEDIUM");
                item.setType("SHORT_ANSWER");
                item.setScore(5.0);
                
                exercises.add(item);
            }
        }
        
        return exercises;
    }
} 